package com.raising.utils;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
 * @author GaoYuan
 * @version 2017-09-26 16:28:41
 */
public class JDateUtils extends org.apache.commons.lang3.time.DateUtils {

	public static String PATTERN_CN = "yyyy年MM月dd日";

	private static String[] parsePatterns = {
		"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
		"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
		"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

	/**
	 * 得到当前日期字符串 格式（yyyy-MM-dd）
	 */
	public static String getDate() {
		return getDate("yyyy-MM-dd");
	}

	/**
	 * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String getDate(String pattern) {
		return DateFormatUtils.format(new Date(), pattern);
	}

	/**
	 * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String formatDate(Date date, Object... pattern) {
		String formatDate = null;
		if (pattern != null && pattern.length > 0) {
			formatDate = DateFormatUtils.format(date, pattern[0].toString());
		} else {
			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
		}
		return formatDate;
	}

	/**
	 * 日期字符串根据格式转日期字符串
	 * @Title: getDateStr
	 * @return String    返回类型
	 * @author xieht
	 * @time 2017-5-11上午10:53:07
	 */
	public static final String getDateStr(String dateStr,String datePattern){
		SimpleDateFormat df;
		if(datePattern!=null && !"".equals(datePattern)){
			df = new SimpleDateFormat(datePattern);
		}else{
			df = new SimpleDateFormat(parsePatterns[0]);
		}
		Date returnValue = null;
		try {
			returnValue = df.parse(dateStr);
			dateStr = df.format(returnValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm:ss）
	 */
	public static String formatDateTime(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 得到当前时间字符串 格式（HH:mm:ss）
	 */
	public static String getTime() {
		return formatDate(new Date(), "HH:mm:ss");
	}

	/**
	 * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
	 */
	public static String getDateTime() {
		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 得到当前年份字符串 格式（yyyy）
	 */
	public static String getYear() {
		return formatDate(new Date(), "yyyy");
	}

	/**
	 * 得到当前月份字符串 格式（MM）
	 */
	public static String getMonth() {
		return formatDate(new Date(), "MM");
	}

	/**
	 * 得到当天字符串 格式（dd）
	 */
	public static String getDay() {
		return formatDate(new Date(), "dd");
	}

	/**
	 * 得到当前星期字符串 格式（E）星期几
	 */
	public static String getWeek() {
		return formatDate(new Date(), "E");
	}

	/**
	 * 日期型字符串转化为日期 格式
	 * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
	 *   "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
	 *   "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
	 */
	public static Date parseDate(Object str) {
		if (str == null){
			return null;
		}
		try {
			return parseDate(str.toString(), parsePatterns);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取过去的天数
	 * @param date
	 * @return
	 */
	public static long pastDays(Date date) {
		long t = System.currentTimeMillis() - date.getTime();
		return t/(24*60*60*1000);
	}

	/**
	 * 获取过去的小时
	 * @param date
	 * @return
	 */
	public static long pastHour(Date date) {
		long t = System.currentTimeMillis() - date.getTime();
		return t/(60*60*1000);
	}

	/**
	 * 获取过去的分钟
	 * @param date
	 * @return
	 */
	public static long pastMinutes(Date date) {
		long t = System.currentTimeMillis() - date.getTime();
		return t/(60*1000);
	}

	/**
	 * 转换为时间（天,时:分:秒.毫秒）
	 * @param timeMillis
	 * @return
	 */
    public static String formatDateTime(long timeMillis){
		StringBuffer buffer = new StringBuffer();
		long day = timeMillis/(24*60*60*1000);
		long hour = (timeMillis/(60*60*1000)-day*24);
		long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
		long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
		long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
		if(day>0){
			buffer.append(day+",");
		}
		if(hour>0){
			buffer.append(hour+":");
		}
		if(min>0){
			buffer.append(min+":");
		}
		if(s>0){
			buffer.append(s+".");
		}
		if(sss>0){
			buffer.append(sss);
		}
		return buffer.toString();
    }

	/**
	 * 获取两个日期之间的天数
	 *
	 * @param before
	 * @param after
	 * @return
	 */
	public static double getDistanceOfTwoDate(Date before, Date after) {
		long beforeTime = before.getTime();
		long afterTime = after.getTime();
		return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
	}

	/**
	 * 【取两个String类型时间相差[天数]】(同一天返回0,根据需要选择是否+1)
	 * @param dateStart 开始时间
	 * @param dateEnd 结束时间
	 * @return 天数[int类型]
	 * @author bail
	 */
	public static int getDiffDaysByDateStr(String dateStart, String dateEnd){
		try{
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			long diff = df.parse(dateEnd).getTime() - df.parse(dateStart).getTime();
			return (int)(diff/1000/60/60/24);
		}catch(ParseException e){
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 获取月的最后一天
	 * @author zhaobx
	 * @createTime 2018-02-09 14:08:17
	 */
	public static String getLastDayOfMonth(int year,int month){
		Calendar cal = Calendar.getInstance();
		// 设置年份
		cal.set(Calendar.YEAR,year);
		// 设置月份
		cal.set(Calendar.MONTH, month-1);
		// 获取某月最大天数
		int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		// 设置日历中月份的最大天数
		cal.set(Calendar.DAY_OF_MONTH, lastDay);
		// 格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String lastDayOfMonth = sdf.format(cal.getTime());
		return lastDayOfMonth;
	}

	/**
	 * @Title: 传入日期返回多长时间以前
	 * @return String    返回类型
	 * @author xieht
	 * @time 2017-6-1上午9:34:58
	 */
	public static String format(Date date) {
		long delta = System.currentTimeMillis() - date.getTime();
        if (delta < 1L * 60000L) {
            long seconds = delta / 1000L;
            return (seconds <= 0 ? 1 : seconds) + "秒前";
        }
        if (delta < 45L * 60000L) {
            long minutes = delta/1000L/60L;
            return (minutes <= 0 ? 1 : minutes) + "分钟前";
        }
        if (delta < 24L * 3600000L) {
            long hours = delta/1000L/60L/60L;
            return (hours <= 0 ? 1 : hours) + "小时前";
        }
        if (delta < 48L * 3600000L) {
            return "昨天";
        }
        if (delta < 30L * 86400000L) {
            long days = delta/1000L/60L/60L/24L;
            return (days <= 0 ? 1 : days) + "天前";
        }
        if (delta < 12L * 4L * 604800000L) {
            long months = delta/1000L/60L/60L/24L/30L;
            return (months <= 0 ? 1 : months) + "月前";
        } else {
            long years = delta/1000L/60L/60L/24L/30L/365;
            return (years <= 0 ? 1 : years) + "年前";
        }
    }

	/**
	 * 昨天
	 * @author GaoYuan
	 * @datetime 2018/1/24 上午11:38
	 */
	public static String getYesterday(){
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		int day=c.get(Calendar.DATE);
		c.set(Calendar.DATE,day-1);
		String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
		return dayBefore;
	}

	/**
	 * 获得指定日期的前一天
	 * @param specifiedDay
	 * @return
	 * @throws Exception
	 */
	public static String getSpecifiedDayBefore(String specifiedDay){
//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		Date date=null;
		try {
			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day=c.get(Calendar.DATE);
		c.set(Calendar.DATE,day-1);

		String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
		return dayBefore;
	}
	/**
	 * 获得指定日期的后一天
	 * @param specifiedDay
	 * @return
	 */
	public static String getSpecifiedDayAfter(String specifiedDay){
		Calendar c = Calendar.getInstance();
		Date date=null;
		try {
			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day=c.get(Calendar.DATE);
		c.set(Calendar.DATE,day+1);

		String dayAfter=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
		return dayAfter;
	}

	/**
	 * 查询指定日期属于一年中的第几周
	 * @author GaoYuan
	 * @datetime 2018/2/1 下午4:09
	 */
	public static String getWeekOfYear() {
		try{
			Calendar calendar = Calendar.getInstance();
			calendar.setFirstDayOfWeek(Calendar.MONDAY);
			calendar.setTime(new Date());
			int week = calendar.get(Calendar.WEEK_OF_YEAR);
			int mouth = calendar.get(Calendar.MONTH);
			// JDK think 2015-12-31 as 2016 1th week
			//如果月份是12月，且求出来的周数是第一周，说明该日期实质上是这一年的第53周，也是下一年的第一周
			if (mouth >= 11 && week <= 1) {
				week += 52;
			}
			return String.valueOf(week);
		}catch (Exception e) {
			return "";
		}
	}
	public static String getWeekOfYear(String dateStr) {
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setFirstDayOfWeek(Calendar.MONDAY);
			calendar.setTime(date);
			int week = calendar.get(Calendar.WEEK_OF_YEAR);
			int mouth = calendar.get(Calendar.MONTH);
			// JDK think 2015-12-31 as 2016 1th week
			//如果月份是12月，且求出来的周数是第一周，说明该日期实质上是这一年的第53周，也是下一年的第一周
			if (mouth >= 11 && week <= 1) {
				week += 52;
			}
			return String.valueOf(week);
		}catch (Exception e) {
			return "";
		}
	}
	public static void main(String[] args){
		try {
			List<Date> list = queryWeekFirstAndEnd("2016-12-31");
			System.out.println(list.get(0)+""+list.get(1));
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	 /**
     * 处理传入的时间格式字符串，获得本周起始时间(不传默认按当前时间算)
     * @author chenem
     */
    public static List<Date> queryWeekFirstAndEnd(String dateStr)throws ParseException{
        /**获取所选日期所在周的第一天和最后一天*/
        /**结果list*/
        List<Date> list = Lists.newArrayList();
        Calendar cal = Calendar.getInstance();
        if (JStringUtils.isNotBlank(dateStr)) {
            cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr));
        }
        /**将时分秒设为*/
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
		//获取当前年份
		Integer year = cal.get(Calendar.YEAR);
		System.out.println(year);
        int d = 0;
        if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
            d = -6;
        } else {
            d = 2 - cal.get(Calendar.DAY_OF_WEEK);
        }
        cal.add(Calendar.DAY_OF_WEEK, d);
        // 所在周开始日期
        Date weekFirstDay = cal.getTime();
        cal.add(Calendar.DAY_OF_WEEK, 6);
        // 所在周结束日期
        Date weekEndDay = cal.getTime();
		//获取该年第一天
		Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        //获取该年最后一天
        Calendar calendar2 = Calendar.getInstance();
        calendar2.clear();
        calendar2.set(Calendar.YEAR, year);
        calendar2.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar2.getTime();
        //如果本周第一天早于本年第一天，则将本年第一天设为本周第一天
        if (weekFirstDay.before(currYearFirst)){
        	weekFirstDay = currYearFirst;
		}
		//如果本周最后一天晚于本年最后一天，则将本年最后一天设为本周最后一天
		if (weekEndDay.after(currYearLast)){
        	weekEndDay = currYearLast;
		}
        list.add(weekFirstDay);
        list.add(weekEndDay);
        return list;
    }


}
